package com.wlts.wzy.DYUserModule.util;

import com.wlts.wzy.Base.BaseEntity;

import com.wlts.wzy.DYUserModule.entity.DyOauth;
import com.wlts.wzy.DYUserModule.entity.DyStoreUser;
import com.wlts.wzy.DYUserModule.service.IDyOauthService;
import com.wlts.wzy.DYUserModule.service.IDyStoreUserService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.response.dy.DyOauthResponse;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class DyTokenUtil {

    @Autowired
    private IDyOauthService ksOauthService;
    @Autowired
    private IDyStoreUserService ksStoreUserService;

    @Scheduled(fixedDelay = 600 * 1000)//10分钟刷新一次

    public void upDateDyToken() {

        MyLambdaQueryWrapper<DyOauth> queryWrapper = new MyLambdaQueryWrapper<>();

        queryWrapper.eq(BaseEntity::getDelFlag, "0");

        queryWrapper.le(DyOauth::getTokenOverTime, LocalDateTime.now().plusHours(12));

        List<DyOauth> ksOauthList = ksOauthService.list(queryWrapper);

        ksOauthList.forEach(ksOauth -> {

            MyLambdaQueryWrapper<DyStoreUser> wrapper = new MyLambdaQueryWrapper<>();

            wrapper.eq(DyStoreUser::getUuid, ksOauth.getUserUuid());

            wrapper.eq(BaseEntity::getDelFlag, "0");

            DyStoreUser ksStoreUser = ksStoreUserService.getOne(wrapper);

            if (ksStoreUser != null) {
                try {
                    DyOauthResponse response = UserUtil.getAccessToken(ksStoreUser.getAppKey(),ksStoreUser.getAppSecret());
                    ksOauth.setUserUuid(ksStoreUser.getUuid());
                    ksOauth.setAccessToken(response.getAccessToken());
                    ksOauth.setRefreshToken(response.getRefreshToken());
                    ksOauth.setExpiresIn(response.getExpiresIn());
                    //  dyOauth.setOpenId(response.getOpenId());
                    //access_token过期时间，单位秒，默认为172800，即48小时
                    ksOauth.setTokenOverTime(LocalDateTime.now().plusSeconds(response.getExpiresIn()));
                    ksOauth.setMessageStatus(0);
                    ksOauth.setTokenStatus(0);
                    ksOauthService.updateById(ksOauth);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        });
        if(ksOauthList.size()>0){
            ksOauthService.updateBatchById(ksOauthList);
        }
    }

}
